import { register } from '@/apis/login'
import { getUserInfo, getGeoIp } from '@/apis/user'
import { requestIP } from '@/apis/extern'
import { _local} from '@/utils/storage'
import {
  setToken, removeToken, setRyToken, removeRyToken,
  setRyId, removeRyId, setSecret, removeSecret,
  setUserId, getUserId, removeUserId, setIp, setGeolocation,
  setLoginStatus, removeLoginStatus, removeHouseList, removeHouseListNew,
  removeHouseListBuy
} from '@/utils/auth'
import { resetRouter } from '@/router'
import store from '@/store'

const getDefaultState = () => {
  return {
    role: 0,
    realNameAuthStatus: false,
    capital: 0,
    integral: 0,
    withdrawAmount: 0,
    agentReview: {
      'checkStatus': 0,
      'certificateUrl': ''
    },
    agent: {
      'agentSn': '',
      'cashDeposit': 0,
      'cautionMoney': 0,
      'time': '',
      'vip': 0,
      'agentAvatar': '',
      'adcode': 0,
      'citycode': ''

    }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },

  SET_ROLE: (state, role) => {
    state.role = role
    _local.set("role",role)
  },

  SET_REAL_NAME_AUTH_STATUS: (state, realNameAuthStatus) => {
    state.realNameAuthStatus = realNameAuthStatus
  },
  SET_CAPITAL: (state, capital) => {
    state.capsule = capital
  },
  SET_INTEGRAL: (state, integral) => {
    state.integral = integral
  },
  SET_WITHDRAW_AMOUNT: (state, withdrawAmount) => {
    state.withdrawAmount = withdrawAmount
  },
  SET_AGENT_REVIEW: (state, agentReview) => {
    state.agentReview = agentReview
  },
  SET_AGENT: (state, agent) => {
    state.agent = agent
    _local.set("agent",JSON.stringify(agent))
  }
}

const actions = {
  // user login
  register(_, payload) {
    const { mobile, verifyCode,city_name} = payload
    return new Promise((resolve, reject) => {
      register({ mobile: mobile.trim(), verifyCode: verifyCode,city_name:city_name}).then(response => {
        const result = response.result
        const code = response.code

        // 成功保存状态
        if (code === 201) {
          const userId = result.userId
          const token = result.token
          const ryId = result.ryId
          const ryToken = result.ryToken
          // 成功缓存token
          setToken(token)
          // 澄清缓存ry token
          setRyToken(ryToken)
          setRyId(ryId)
          setUserId(userId)
          setLoginStatus(1)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      const userId = getUserId()
      getUserInfo({ userId: userId }).then((response) => {
        const code = response.code
        const result = response.result
        if (code === 201) {
          // console.log('rev', result.AgentReview)
          const username = result.realname
          const mobile = result.mobile
          const realNameAuthStatus = result.realNameAuthStatus
          const role = result.role
          _local.set("role",role)
          const capital = result.capital
          const integral = result.integral
          const withdrawAmount = result.withdrawAmount
          const avatar = result.avatar
          const agentReview = Object.assign({}, result.AgentReview)
          const agent = Object.assign({}, result.agent)
          _local.set("agent",JSON.stringify(agent))
          
          commit('SET_REAL_NAME_AUTH_STATUS', realNameAuthStatus)
          commit('SET_CAPITAL', capital)
          commit('SET_ROLE', role)
          commit('SET_INTEGRAL', integral)
          commit('SET_WITHDRAW_AMOUNT', withdrawAmount)
          commit('SET_AGENT_REVIEW', agentReview)
          commit('SET_AGENT', Object.assign({}, agent))
          // 用户标识
          const secret = { 'mobile': mobile, 'username': username, 'avatar': avatar }
          setSecret(secret)
        }

        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getIp() {
    return new Promise((resolve, reject) => {
      requestIP().then(response => {
        const data = response.data
        const array = data.split('=')
        const str = array[1].trim()
        const jsonStr = str.slice(0, str.length - 1)
        const obj = JSON.parse(jsonStr)

        console.log('obj.ip:', obj.ip)

        setIp(obj.ip)
        resolve(obj)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getGeolocation(_, ipAddress) {
    return new Promise((resolve, reject) => {
      getGeoIp({ ipAddress: ipAddress }).then(response => {
        const code = response.code
        const result = response.result

        if (code === 201) {
          const cityCode = result.citycode
          const adCode = result.adcode
          const city = result.city
          const district = result.district

          setGeolocation(cityCode, city, adCode, district)
        } else {
          // 默认值
          setGeolocation('028', '510107', '成都市', '武侯区')
        }

        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    commit('SET_REAL_NAME_AUTH_STATUS', 0)
    commit('SET_CAPITAL', 0)
    commit('SET_ROLE', 0)
    commit('SET_INTEGRAL', 0)
    commit('SET_WITHDRAW_AMOUNT', 0)
    commit('SET_AGENT_REVIEW', {})
    commit('SET_AGENT', {})

    store.dispatch('im/setConnect', { connect: false })
    store.dispatch('im/setConversation', { conversation: {}})
    store.dispatch('im/setConversationNum', { num: 0 })
    store.dispatch('im/setConversationList', { conversationList: [] })
    store.dispatch('im/setRecord', { record: [] })
    store.dispatch('im/setHasMore', { hasMore: false })
    store.dispatch('im/setHistoryTimestamp', { historyTimestamp: 0 })

    removeToken()
    removeRyToken()
    removeRyId()
    removeUserId()
    removeSecret()
    removeLoginStatus()
    removeHouseList()
    removeHouseListBuy()
    removeHouseListNew()
    // must remove  token  first
    resetRouter()
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

